package com.platform.cdcs.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.v4.content.ContextCompat;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.MyApp;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.custom.EditPriceNumFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.DocNo;
import com.platform.cdcs.model.InvoiceList;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.platform.cdcs.widget.FormDialog;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.model.ChooseItem;
import com.trueway.app.uilib.tool.Utils;
import com.trueway.app.uilib.widget.NoScrollGridView;
import com.trueway.app.uilib.widget.TwDialogBuilder;
import com.tubb.smrv.SwipeHorizontalMenuLayout;
import com.tubb.smrv.SwipeMenuLayout;
import com.tubb.smrv.listener.SwipeSwitchListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.w3c.dom.Text;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/9/25.
 */
public class TicketRelationFragment extends BaseFragment {

    private ItemAdapter itemAdapter;
    private String id, cusCode, inNo;
    private DocNo docNo;
    private int pageIndex = 1;
    private ObservableXListView listView;
//    private CodeAdapter codeAdapter;
    private SwipeMenuLayout currentSwipeLayout;
    private XListView.OnXScrollListener scrollListener = new XListView.OnXScrollListener() {
        @Override
        public void onXScrolling(View view) {
        }

        @Override
        public void onScrollStateChanged(AbsListView absListView, int i) {

        }

        @Override
        public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            itemAdapter.closeSlide();
        }
    };
    private SwipeSwitchListener swipeListener = new SwipeSwitchListener() {
        @Override
        public void beginMenuClosed(SwipeMenuLayout swipeMenuLayout) {
        }

        @Override
        public void beginMenuOpened(SwipeMenuLayout swipeMenuLayout) {
            if (currentSwipeLayout != null && swipeMenuLayout != currentSwipeLayout) {
                currentSwipeLayout.smoothCloseBeginMenu();
            }
            currentSwipeLayout = swipeMenuLayout;
        }

        @Override
        public void endMenuClosed(SwipeMenuLayout swipeMenuLayout) {
        }

        @Override
        public void endMenuOpened(SwipeMenuLayout swipeMenuLayout) {
            if (currentSwipeLayout != null && swipeMenuLayout != currentSwipeLayout) {
                currentSwipeLayout.smoothCloseEndMenu();
            }
            currentSwipeLayout = swipeMenuLayout;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        itemAdapter = new ItemAdapter(getContext());
//        codeAdapter = new CodeAdapter(getContext());
        id = getArguments().getString("id");
        cusCode = getArguments().getString("cusCode");
        inNo = getArguments().getString("inNo");
    }

//    private void requestDetail(final boolean flag) {
//        if (flag) {
//            showLoadImg();
//        }
//        Map<String, String> param = new HashMap<>();
//        param.put("id", id);
//        param.put("cusCode", cusCode);
//        param.put("type", "0");
//        getHttpClient().post().url(Constant.LIST_FOR_INVOICE).params(Constant.makeParam(param)).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                if (flag) {
//                    dismissLoadImg();
//                }
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                if (flag) {
//                    dismissLoadImg();
//                }
//                Type type = new TypeToken<BaseObjResponse<DocNo>>() {
//                }.getType();
//                BaseObjResponse<DocNo> response = new Gson().fromJson(s, type);
//                if ("1".equals(response.getResult().getCode())) {
//                    docNo = response.getResult();
//                    if (docNo.getDocList().size() > 0) {
//                        codeAdapter.clear();
//                        codeAdapter.addAll(docNo.getDocList());
//                        if (flag) {
//                            showDoc();
//                        }
//                    } else {
//                        codeAdapter.clear();
//                    }
//                    codeAdapter.notifyDataSetChanged();
//                } else {
//                    Utils.showToast(getContext(), response.getResult().getMsg());
//                }
//
//            }
//        });
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void initView(View view) {
        initLoadImg(view.findViewById(R.id.load));
        view.findViewById(R.id.activity_main_toolbar).setVisibility(View.GONE);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        setTitle("关联产品");
        View headerView = LayoutInflater.from(getContext()).inflate(R.layout.ticket_header, null);
//        NoScrollGridView gridView = (NoScrollGridView) headerView.findViewById(R.id.list);
//        gridView.setClick(true);
//        gridView.setAdapter(codeAdapter);
        headerView.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentUtil.navigateToInNewActivity(getActivity(), TicketChooseFragment.class, getArguments());
            }
        });
        listView = (ObservableXListView) view.findViewById(android.R.id.list);
        listView.setPullRefreshEnable(true);
        listView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                itemAdapter.clear();
                itemAdapter.notifyDataSetChanged();
//                requestDetail(false);
                requestProduct(false);
            }

            @Override
            public void onLoadMore() {
                requestProduct(false);
            }
        });
        listView.addHeaderView(headerView);
        listView.setOnScrollListener(scrollListener);
        listView.setAdapter(itemAdapter);
//        requestDetail(true);
        requestProduct(true);
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

//    private void editQty(final ProductList.ProductItem item, final String num, final SwipeHorizontalMenuLayout menu) {
//        showLoadImg();
//        Map<String, String> map = new HashMap<>();
//        map.put("inId", item.getId());
//        map.put("qty", num);
//        getHttpClient().post().url(Constant.EDIT_INVOICE_PRODUCTFORAPP).params(Constant.makeParam(map)).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int i) {
//                dismissLoadImg();
//                Utils.showToast(getContext(), R.string.server_error);
//            }
//
//            @Override
//            public void onResponse(String s, int i) {
//                try {
//                    dismissLoadImg();
//                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
//                    }.getType();
//                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
//                    if ("1".equals(response.getResult().getCode())) {
//                        menu.smoothCloseMenu();
//                        item.setQty(num);
//                        itemAdapter.notifyDataSetChanged();
//                        Utils.showToast(getContext(), "数量设置成功");
//                    } else {
//                        Utils.showToast(getContext(), response.getResult().getMsg());
//                    }
//                } catch (Exception e) {
//
//                }
//            }
//        });
//    }

//    private class CodeAdapter extends EnhancedAdapter<DocNo.DocItem> {
//
//
//        public CodeAdapter(Context context) {
//            super(context);
//        }
//
//        @Override
//        protected void bindView(View paramView, Context paramContext, int position) {
//            TextView textView = (TextView) paramView;
//            textView.setText(getItem(position).getDocNo());
//        }
//
//        @Override
//        protected View newView(Context context, int position, ViewGroup viewgroup) {
//            TextView textView = new TextView(getContext());
//            int padding = Utils.convertDIP2PX(getContext(), 3);
//            textView.setPadding(padding * 3, padding, padding * 3, padding);
//            textView.setTextSize(12);
//            textView.setTextColor(ContextCompat.getColor(getContext(), R.color.text_dark));
//            textView.setBackgroundResource(R.drawable.bg_gray_rect);
//            return textView;
//        }
//
//        public String getAllIds() {
//            String ids = "";
//            for (DocNo.DocItem item : dataList) {
//                ids += item.getDocNo() + ",";
//            }
//            if (!TextUtils.isEmpty(ids)) {
//                ids = ids.substring(0, ids.length() - 1);
//            }
//            return ids;
//        }
//    }

    private void requestProduct(boolean load) {
        if (load) {
            showLoadImg();
        }
        Map<String, String> map = new HashMap<>();
        map.put("cusCode", cusCode);
//        map.put("distCode", MyApp.getInstance().getAccount().getOrgId());
        map.put("inNo", inNo);
//        map.put("docNo", codeAdapter.getAllIds());
        map.put("pageSize", String.valueOf(Constant.PAGE_SIZE));
        map.put("pageIndex", String.valueOf(pageIndex));
        getHttpClient().post().url(Constant.INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                listView.stopLoadMore();
                listView.stopRefresh();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                listView.stopLoadMore();
                listView.stopRefresh();
                Type type = new TypeToken<BaseObjResponse<ProductList>>() {
                }.getType();
                BaseObjResponse<ProductList> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    itemAdapter.addAll(response.getResult().getProductList());
                    itemAdapter.notifyDataSetChanged();
                    if (response.getResult().getProductList().size() == Constant.PAGE_SIZE) {
                        listView.setPullLoadEnable(true);
                    } else {
                        listView.setPullLoadEnable(false);
                    }
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            pageIndex = 1;
            itemAdapter.clear();
            itemAdapter.notifyDataSetChanged();
            requestProduct(false);
        }
    }

    private void removeProduct(ProductList.ProductItem item, final SwipeHorizontalMenuLayout menu) {
        itemAdapter.closeSlide();
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("id", item.getId());
        map.put("inId", id);

        getHttpClient().post().url(Constant.CANCEL_INVOICE_PRODUCT).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                }.getType();
                BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    menu.smoothCloseMenu();
                    pageIndex = 1;
                    itemAdapter.clear();
                    itemAdapter.notifyDataSetChanged();
                    requestProduct(true);
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    private SpannableString formatS(int len, String msg) {
        SpannableString ss = new SpannableString(msg);
        ss.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.gray_text)), 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    public void closeSlide() {
        if (currentSwipeLayout != null) {
            try {
                currentSwipeLayout.smoothCloseBeginMenu();
                currentSwipeLayout.smoothCloseEndMenu();
                currentSwipeLayout = null;
            } catch (Exception e) {

            }
        }
    }

    private class ItemAdapter extends EnhancedAdapter<ProductList.ProductItem> {

        private View.OnClickListener leftListener = new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                final ProductList.ProductItem item = (ProductList.ProductItem) view.getTag();
//                new FormDialog(getContext(), new FormDialog.FormListener() {
//                    @Override
//                    public void okClick(String[] value) {
//                        editQty(item, value[0], (SwipeHorizontalMenuLayout) view.getTag(R.id.left));
//                    }
//                }, "编辑产品数量").addView(new String[]{"产品数量"}, 0, item.getQty()).show();
                Bundle bundle = new Bundle();
                bundle.putString("itemCode", item.getItemCode());
                bundle.putString("cusCode", item.getCusCode());
                bundle.putString("inId", id);
                bundle.putString("pid", item.getId());
                FragmentUtil.navigateToInNewActivity(getActivity(), EditPriceNumFragment.class, bundle);
                itemAdapter.closeSlide();
            }
        };
        private View.OnClickListener rightListener = new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                final ProductList.ProductItem item = (ProductList.ProductItem) view.getTag();
                new TwDialogBuilder(getContext()).setTitle(R.string.attention).setMessage("确定是否移除吗？").setPositiveButton(R.string.cancel_text, null).setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        removeProduct(item, (SwipeHorizontalMenuLayout) view.getTag(R.id.right));
                    }
                }).create().show();
            }
        };

        public ItemAdapter(Context context) {
            super(context);
        }

        public void closeSlide() {
            if (currentSwipeLayout != null) {
                try {
                    currentSwipeLayout.smoothCloseBeginMenu();
                    currentSwipeLayout.smoothCloseEndMenu();
                    currentSwipeLayout = null;
                } catch (Exception e) {

                }
            }
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            ProductList.ProductItem item = getItem(position);
            holder.titleView.setText(item.getItemCode());
            holder.timeView.setText(item.getQty() + " " + item.getUom());
            holder.textView.setText(item.getItemName());
            holder.leftBtn.setTag(item);
            holder.rightBtn.setTag(item);
            holder.leftBtn.setTag(R.id.left, holder.menu);
            holder.rightBtn.setTag(R.id.right, holder.menu);
            SwipeMenuLayout sLayout = holder.menu;
            sLayout.setTag(R.id.button1, item);
            holder.priceTV.setText( item.getProductPrice());
            holder.numTV.setText(item.getQty());
            holder.totalTV.setText( item.getTotalPrice());
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = inflater.inflate(R.layout.stock_item_group, viewgroup, false);
            rootView.findViewById(R.id.bar1).setVisibility(View.VISIBLE);
            rootView.findViewById(R.id.bar2).setVisibility(View.VISIBLE);
            rootView.setBackgroundResource(R.drawable.shape_corner_center);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            holder.titleView.getPaint().setFakeBoldText(true);
            holder.timeView = (TextView) rootView.findViewById(R.id.time);
            holder.textView = (TextView) rootView.findViewById(R.id.text);
            holder.textView.setSingleLine(false);
            holder.priceTV = (TextView) rootView.findViewById(R.id.title1);
            holder.numTV = (TextView) rootView.findViewById(R.id.title2);
            holder.totalTV = (TextView) rootView.findViewById(R.id.title3);
            holder.leftBtn = (TextView) rootView.findViewById(R.id.smMenuViewLeft);
            holder.rightBtn = (TextView) rootView.findViewById(R.id.smMenuViewRight);
            holder.leftBtn.setOnClickListener(leftListener);
            holder.rightBtn.setOnClickListener(rightListener);
            holder.menu = (SwipeHorizontalMenuLayout) rootView.findViewById(R.id.sml);
            holder.menu.setSwipeListener(swipeListener);
            rootView.setTag(holder);
            return rootView;
        }
    }

    private class ViewHolder {
        TextView titleView, timeView, textView, leftBtn, rightBtn, priceTV, numTV, totalTV;
        SwipeHorizontalMenuLayout menu;
    }
}